import { Editor, Element, Transforms } from "slate";
import { useSlate } from "slate-react";

const LIST_TYPES: Array<string> = ["numbered-list", "bulleted-list"];
const BLOCK_NODE: Array<string> = [];
const TEXT_ALIGN_TYPES: Array<string> = ["style-textAlign"];

export default () => {
  const editor = useSlate();

  const isBlockActive = (format: string, value = "type") => {
    const { selection } = editor;
    if (!selection) return false;

    const [match] = Array.from(
      Editor.nodes(editor, {
        at: Editor.unhangRange(editor, selection),
        match: (n: any) => {
          return (
            !Editor.isEditor(n) && Element.isElement(n) && n?.[value] === format
          );
        },
      })
    );
    return !!match;
  };

  const markBlockValue = (format: string) => {
    const { selection } = editor;
    if (!selection) return false;

    const list: any = [];
    const nodes = Array.from(
      Editor.nodes(editor, {
        at: Editor.unhangRange(editor, selection),
        match: (n: any) => {
          return (
            !Editor.isEditor(n) &&
            Element.isElement(n) &&
            Editor.isBlock(editor, n) &&
            n?.[format]
          );
        },
      })
    );

    nodes.forEach((item:any) => {
      const v = item?.[0]?.[format];
      if (v && !list.includes(v)) {
        list.push(v);
      }
    });

    return list.length === 1 ? list?.[0] : undefined;
  };

  const toggleBlockMark = (format: string, value?: any) => {
    const key = LIST_TYPES.includes(format) ? "type" : format;

    const isActive = isBlockActive(format, value);

    Transforms.unwrapNodes(editor, {
      match: (n:any) =>
        !Editor.isEditor(n) &&
        Element.isElement(n) &&
        LIST_TYPES.includes(n?.type) &&
        !TEXT_ALIGN_TYPES.includes(format),
      split: true,
    });


    Transforms.setNodes(editor, {
      [key]:
        key === "type"
          ? isActive
            ? "paragraph"
            : "list-item"
          : isActive
          ? undefined
          : value,
    });

    if (!isActive && LIST_TYPES.includes(format)) {
      const block = { type: format, children: [] };
      Transforms.wrapNodes(editor, block);
    }
  };

  return {
    isBlockActive,
    markBlockValue,
    toggleBlockMark,
  };
};
